import { orderRequest } from '@core/utils/request';
import EnvConfig from '@core/utils/EnvConfig';
import HistoryHelper from '@core/utils/HistoryHelper';
import Session from '@core/engine/Session';

export default class Order {
  static buildOrderParams = (options: OrderParamsBuilderOptions) => {
    const { orderDetail, resourceDetail, ...otherParams } = options;
    const formattedParams: Record<string, string | number | boolean> = {};
    if (orderDetail) {
      formattedParams.orderDetailJson = JSON.stringify(orderDetail);
    }
    if (resourceDetail) {
      formattedParams.resourceDetailJson = JSON.stringify(resourceDetail);
    }
    return { ...formattedParams, ...otherParams };
  };

  static buildCustomInfo = (): CustomInfo => {
    return {
      type: 2,
      identity: { accountId: Session.getAccountId() },
    };
  };

  /**
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-31
   */
  static queryNewPurchaseOrderPrice = (orderDetail: QueryNewOrderParams) => {
    return orderRequest.post<QueryNewOrderParams, QueryOrderResponse>(
      'ctcloud/bsscrm/order_queryNewPurchaseOrderPrice/queryNewPurchaseOrderPrice',
      Order.buildOrderParams({ orderDetail }),
    );
  };

  /**
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-8
   */
  static placeNewPurchaseOrder = (orderDetail: PlacePurchaseOrderParams) => {
    return orderRequest.post<PlacePurchaseOrderParams, PlaceOrderResponse>(
      'ctcloud/bsscrm/orderplaceNewPurchaseOrder',
      Order.buildOrderParams({ orderDetail: { ...orderDetail, customInfo: Order.buildCustomInfo() } }),
    );
  };

  /**
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-32
   */
  static queryRenewOrderPrice = (resourceDetail: RenewOrderParams) => {
    return orderRequest.post<RenewOrderParams, Array<QueryOrderResponse>>(
      'ctcloud/bsscrm/order_queryRenewOrderPrice/queryRenewOrderPrice',
      Order.buildOrderParams({ resourceDetail }),
    );
  };

  /**
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-12
   */
  static placeRenewOrder = (resourceDetail: RenewOrderParams) => {
    return orderRequest.post<RenewOrderParams, OrderPlaceEventsResponse>(
      'ctcloud/bsscrm/order_placeRenewOrder/placeRenewOrder',
      Order.buildOrderParams({ resourceDetail }),
    );
  };

  /**
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-32
   */
  static queryUpgradeOrderPrice = (orderDetail: UpdateOrderParams) => {
    return orderRequest.post<UpdateOrderParams, QueryOrderResponse>(
      'ctcloud/bsscrm/order_queryUpgradeOrderPrice',
      Order.buildOrderParams({ orderDetail: { ...orderDetail, customInfo: Order.buildCustomInfo() } }),
    );
  };

  /**
   * 参数、返回值与查询升级订单 api 相同
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-32
   */
  static queryDegradeOrderPrice = (orderDetail: UpdateOrderParams) => {
    return orderRequest.post<UpdateOrderParams, QueryOrderResponse>(
      'ctcloud/bsscrm/queryDegradeOrderPrice',
      Order.buildOrderParams({ orderDetail: { ...orderDetail, customInfo: Order.buildCustomInfo() } }),
    );
  };

  /**
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-13
   */
  static placeUpgradeOrder = (orderDetail: UpdateOrderParams) => {
    return orderRequest.post<UpdateOrderParams, PlaceOrderResponse>(
      'ctcloud/bsscrm/v3_order_placeUpgradeOrder',
      Order.buildOrderParams({ orderDetail: { ...orderDetail, customInfo: Order.buildCustomInfo() } }),
    );
  };

  /**
     * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-79
     */
  static placeDegradeOrder = (orderDetail: UpdateOrderParams) => {
    return orderRequest.post<UpdateOrderParams, PlaceOrderResponse>(
      'ctcloud/bsscrm/placeDegradeOrder',
      Order.buildOrderParams({ orderDetail: { ...orderDetail, customInfo: Order.buildCustomInfo() } }),
    );
  };

  /**
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-14
   */
  static placeRefundOrder = (resourceDetail: OrderRefundParams) => {
    return orderRequest.post<OrderRefundParams, PlaceOrderResponse>(
      'ctcloud/bsscrm/order_placeRefundOrder/placeRefundOrder',
      Order.buildOrderParams({ resourceDetail, type: 2 }),
    );
  };

  /**
   * @see https://eop.ctyun.cn/api-proxy/docs/crm/#1-11
   */
  static queryResourcesByMaster = (masterOrderId: string) => {
    return orderRequest.get<{ masterOrderId: string }, Array<OrderResource>>(
      'ctcloud/bsscrm/queryResourceInfoByMasterOrderId/queryResourceInfoByMasterOrderId',
      { params: Order.buildOrderParams({ masterOrderId, customInfo: Order.buildCustomInfo() }) },
    );
  };

  static openOrderDetailPage = (orderId: string) => {
    const paymentUrl = EnvConfig.isConnectToProduction()
      ? 'http://www.ctyun.cn/h5/bcc/order/pay?orderId='
      : 'https://wwwtest.ctyun.cn:21443/h5/bcc/order/detail?orderId=';
    HistoryHelper.openNewTab(`${paymentUrl}${orderId}`);
  };
}

export type OrderParamsBuilderOptions = {
  orderDetail?: (QueryNewOrderParams
    | PlacePurchaseOrderParams
    | UpdateOrderParams)
    & { customInfo?: CustomInfo },
  resourceDetail?: (RenewOrderParams | OrderRefundParams),
} & { [P in string]: any }

export interface OrderResourceParams {
  master: boolean,
  resourceType: string,
  serviceTag: string,
  itemConfig: Record<string, string | number | boolean>,
  itemValue: number,
  resourceId?: string,
}

export interface OrderParams {
  instanceCnt: number,
  cycleCnt?: number,
  cycleType?: number,
  items: Array<OrderResourceParams>,
}

export interface QueryNewOrderParams {
  orders: Array<OrderParams>,
}

export interface PlaceOrderParams {
  id?: string,
  sellingPrice?: number,
  isPlatformSpecificResource?: string,
  billingOwner?: number,
  isPackage?: boolean,
  chargeOffType?: number,
  paymentPlanInitialMonth?: string,
  autoPay?: boolean,
}

export interface PlacePurchaseOrderParams extends PlaceOrderParams {
  packageType?: number,
  autoRenewStatus?: number,
  autoRenewCycleType?: number,
  autoRenewCycleCount?: number,
  userChannelLimitation?: string,
  orders: Array<OrderParams>,
}

export interface RenewOrderParams extends PlaceOrderParams {
  packageType?: number,
  resourceIds: Array<string>,
  cycleCount: number,
  cycleType: number,
}

export interface UpdateOrderParams extends PlaceOrderParams {
  orders: Array<OrderParams>,
}

export interface OrderRefundParams {
  resourceDetailJson: {
    resources: Array<{ resourceIds: Array<string> }>,
    autoApproval: boolean,
  },
  type: number,
}

export interface QueryOrderResponse {
  totalPrice: number,
  finalPrice: number,
  itemId: string,
  resourceType: string,
}

export interface PlaceOrderResponse {
  newOrderId: string,
  newOrderNo: string,
  totalPrice: number,
}

export interface OrderPlaceEventsResponse {
  submitted: boolean,
  orderPlacedEvents: Array<PlaceOrderResponse>,
}

export interface PlaceRefundOrderResponse {
  batchOrderPlacementResults: Array<OrderPlaceEventsResponse>,
}

export interface OrderResource {
  orderItemId: string,
  instanceId: string,
  accountId: string,
  userId: string,
  innerOrderId: string,
  innerOrderItemId: string,
  productId: string,
  masterOrderId: string,
  orderId: string,
  masterResourceId: string,
  resourceId: string,
  serviceTag: string,
  resourceType: string,
  resourceInfo: string,
  startDate: string,
  expireDate: number,
  createDate: number,
  updateDate: number,
  status: string,
  workOrderId: string,
  workOrderItemId: string,
  abandonStatus: string,
  salesEntryId: string,
  orderStatus: string,
  itemValue: string,
  chargingStatus: string,
  chargingDate: string,
  resourceConfig: string,
}

export interface CustomInfo {
  type: number,
  identity?: {
    accountId?: string,
  },
}
